<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

// 日期范围
const daterange = ref([Date.now(), Date.now()])
function onDaterangeChange(r: any) {
  console.log(daterange.value)
}

// 统计图切换按钮
const activeIndex = ref(0)

const props = defineProps<{
  buttons: string[]
  data: {
    date: string[]
    value: number[]
  }
}>()

// 统计图
const chartRef = ref(null)
// 存储图表实例
let chartInstance: any = null
onMounted(() => {
  // 初始化图表实例
  chartInstance = echarts.init(chartRef.value)

  // 配置图表选项
  const option = {
    xAxis: {
      data: props.data.date,
    },
    yAxis: {},
    series: [
      {
        type: 'line',
        data: props.data.value,
        smooth: true,
        lineStyle: { color: '#5470C6' },
        areaStyle: {
          color: 'rgba(84, 112, 198, 0.3)', // 带透明度的固定颜色（0.3 为透明度）
        },
      },
    ],
  }

  // 设置图表选项
  chartInstance.setOption(option)
})

// 监听窗口大小变化，自适应图表
const handleResize = () => {
  chartInstance.resize()
}
window.addEventListener('resize', handleResize)

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance.dispose()
})
</script>

<template>
  <div>
    <div class="bar-container">
      <!-- 日期范围 -->
      <el-date-picker
        v-model="daterange"
        type="daterange"
        range-separator="~"
        @change="onDaterangeChange"
        style="flex: 0 0 auto; width: 220px"
      />

      <!-- 统计图切换按钮 -->
      <div class="button-group">
        <el-button
          v-for="(item, index) in props.buttons"
          :key="index"
          :type="activeIndex === index ? 'primary' : 'default'"
          size="small"
          @click="activeIndex = index"
        >
          {{ item }}
        </el-button>
      </div>

      <!-- 导出 -->
      <div>
        <el-button>导出</el-button>
      </div>
    </div>

    <!-- 统计图 -->
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<style scoped>
.bar-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
}

.chart-container {
  width: 100%;
  height: 400px; /* 必须设置高度，否则图表不显示 */
}
</style>
